import logging

from django.urls import path

from oracle.base.baseview import render_handler
from gideon.service.starlabs import GideonHandler, Option
from supergirl.forms.userinfoforms import UserInfoAddModelForm, UserInfoChangeModelForm, UserInfoResetPasswordForm

logger = logging.getLogger(__name__)


class UserInfoHandler(GideonHandler):
    display_list = ["nickname", "gender", "phone", "email", "depart"]
    # 搜索框，定义搜索内容，搜索条件都是django queryset类型的filter方法参数，需要符合对应规则
    search_list = ["nickname__contains", "name__contains"]
    # 快速筛选框
    search_group = [
        Option("gender"),
        Option("depart", is_multi=True),
    ]

    # 运行时返回不同Form
    def get_model_form_class(self, handler_type=None, *args, **kwargs):
        if handler_type == self.get_handler_add_view_type():
            return UserInfoAddModelForm
        elif handler_type == self.get_handler_change_view_type():
            return UserInfoChangeModelForm
        return super(UserInfoHandler, self).get_model_form_class(handler_type, *args, **kwargs)

    # 修改时外键部门id需要重新定义为key
    def get_model_form(self, handler_type, model_form_class, instance=None, *args, **kwargs):
        if handler_type == self.get_handler_change_view_type():
            if self.request.method == 'GET':
                # 默认含外键时，外键显示id这里我们主动的将id更新为key值
                return model_form_class(instance=instance, initial={"depart": instance.depart.key})
        return super(UserInfoHandler, self).get_model_form(handler_type, model_form_class, instance, *args, **kwargs)

    # 显示操作按钮，新增一个重置密码按钮
    def show_options_button(self, obj=None, is_header=True, *args, **kwargs):
        data = super().show_options_button(obj, is_header, *args, **kwargs)
        if obj and isinstance(data, list):
            # 重置密码按钮
            title = "重置密码"
            url = self.reverse_handle_url(self.request, self.get_url_name('reset_password'), key=obj.key)
            key = "reset_password"
            data.append({"title": title, "url": url, "key": key})
        return data

    # 重置密码url获取添加
    def get_extra_urls(self):
        patterns = [
            path(r'resetpassword/<slug:key>/', self.reset_password, name=self.get_url_name('reset_password')),
        ]
        return patterns

    #  重置密码处理
    def reset_password(self, request, key):
        """
        重置密码的视图函数
        :param request:
        :param key:
        :return:
        """
        self.initialize(request)
        userinfo_object = self.model_class.objects.filter(key=key).first()
        status = "success"
        data = {}
        template = None
        if not userinfo_object:
            status = "gideon_change_password_user_not_exist"
            data.update(
                {
                    "head_title": "用户不存在",
                    "title": "用户不存在，无法进行密码重置！",
                    "href": self.reverse_url_list(request),
                    "button_text": "返回用户列表"
                }
            )
        else:
            data['form_name'] = f'重置 {userinfo_object} 的密码'
            if request.method == 'GET':
                data['form'] = UserInfoResetPasswordForm
                template = self.get_template_names("change")
                self.change_form_data_type(data)
            else:
                # 构造 form 实例
                form = UserInfoResetPasswordForm(data=request.POST)
                # form 是否有效
                if form.is_valid():
                    # 获取加密后的密码
                    userinfo_object.password = form.cleaned_data['password']
                    # 保存数据
                    try:
                        userinfo_object.save()
                        # 数据库保存成功跳转回列表页面
                        data.update(
                            {
                                "head_title": "密码修改成功",
                                "title": "用户密码修改成功",
                                "href": self.reverse_url_list(request),
                                "button_text": "返回列表页"
                            }
                        )
                    except Exception as e:
                        logger.error(f"用户重置密码时出错，错误原因为{e}")
                        # 数据库保存失败进行提示
                        status = "form_save_failed"
                        data.update(
                            {
                                "head_title": "密码修改失败",
                                "title": "数据校验通过，最后存储时保存失败",
                            }
                        )
                else:
                    data["form"] = form
                    template = self.get_template_names("change")
                    self.change_form_data_type(data)
        return render_handler(request, status, template=template, data=data)

    def saving_post_handler(self, form, is_update=False, *args, **kwargs):
        if not is_update:
            form.save_m2m()
        return True
